package com.zp.security.oauth2.customized.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.zp.common.base.constant.Atom;
import com.zp.common.base.dao.RoleRepository;
import com.zp.common.base.dao.UserRepository;
import com.zp.common.base.dao.UserRoleRepository;
import com.zp.common.base.entity.SecurityUser;
import com.zp.common.base.entity.User;
import com.zp.common.base.entity.UserRole;
import com.zp.common.base.utils.AuthorizationUtils;
import com.zp.security.oauth2.customized.service.EmailCodeUserDetailService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 自定义邮箱加载用户信息
 *
 * @author zp
 */
@Service
@RequiredArgsConstructor
public class EmailCodeUserDetailServiceImpl implements EmailCodeUserDetailService {
    private final UserRepository userRepository;
    private final UserRoleRepository userRoleRepository;
    private final RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByEmail(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmailandStatus(email, Atom.CONSTANT_ONE);
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("该用户不存在");
        }

        List<UserRole> userRoles = userRoleRepository.findByUserIdAndStatus(user.getUserId(), Atom.CONSTANT_ONE);
        List<String> roles=new ArrayList<>();
        for (UserRole userRole : userRoles) {
            String role = roleRepository.selectById(userRole.getRoleId()).getName();
            roles.add(role);
        }
        SecurityUser securityUser=new SecurityUser();
        securityUser.setUsername(user.getUsername())
                .setPassword(user.getPassword())
                .setTelephone(user.getTelephone())
                .setEmail(user.getEmail())
                .setAuthorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles,String.class)));

        return securityUser;
    }
}
